<?php
require 'framework/phpanalysis/phpanalysis.class.php';

/**
 * 网站搜索时用于拆分搜索字符串 
 *
 */

class analysisHandler {
	
	/**
	 * 分词结果(数组) 
	 * 例如 array('研究','生命','起源')
	 */
	private $analysisArray = array();
	
	/**
	 * 分词结果(字符串)
	 * 例如 '研究 生命 起源'
	 */
	private $analysisString = '';
	
	/**
	 * 拆分分词
	 *
	 * @param string $splitWords 拆分字符串
	 */
	public function analysisWord( $splitWords ) {
		
		$do_fork = $do_unit = true;
		$do_multi = $do_prop = $pri_dict = false;
		
		 //初始化类
	    PhpAnalysis::$loadInit = false;
	    $pa = new PhpAnalysis('utf-8', 'utf-8', $pri_dict);
	    
	    //载入词典
	    $pa->LoadDict();
	   	
	    //执行分词
	    $pa->SetSource( $splitWords );
	    $pa->differMax = $do_multi;
	    $pa->unitWord = $do_unit;
	    
	    $pa->StartAnalysis( $do_fork );
	    
	    $this->analysisString = $pa->GetFinallyResult(' ', $do_prop);
	    
	    $this->analysisArray = explode(' ', trim( $this->analysisString));
	    
	    return $this->analysisArray;
	}
	
	/**
	 * PHP站内搜索功能中匹配的字符串高亮提示
	 *
	 * @param string $title 查找的字符串
	 * @return unknown
	 */
	public function highlightWord( $title ) {
		
		if (!empty($this->analysisArray)) {
			foreach ($this->analysisArray as $w) {
				//正则替换
				$title = preg_replace("/($w)/i","<b style=\"color:#CC0000\">\\1</b>",$title); 
			}
		}
		
		return $title;
	}
	
	/**
	 * 获取关键字搜索的商品数量
	 * 
	 * @param string $splitWords 拆分字符串
	 * @param dbca $dbca 数据库对象
	 * @param array(
	 * 				'count' => 0,
	 * 				'keywords' => array()
	 * 			)
	 */
	public function searchGoodsInfo( $splitWords, $dbca ) {
		
		//拆分分词
		$keyWords = $this->analysisWord( $splitWords );
		$sql = '';
		if ($keyWords) {
			foreach ($keyWords as $word) {
				$sql .= " OR gk.keyword LIKE '%".$word."%'";
			}
		}
		
		if ($sql) {
            $sql = 'WHERE gl.useFlg = 1 AND gl.forsale = 1 AND ('.substr($sql, 3).')';
        }
		
        //统计分类数量
        $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_list gl JOIN goods_keyword gk ON gl.postID = gk.postID ' . $sql;
		$count_array = &$dbca->stmt_query($search_sql);
		if (isset($count_array[0]->item_count)) {
			$count = $count_array[0]->item_count;
		} else {
			$count = 0;
		}
        
		return array( 'keywords' => $keyWords,  'count' => $count);
		
	}
	
}